package cn.tedu.lucky.draw.server.service.impl;

import cn.tedu.lucky.draw.server.common.enums.DrawEnum;
import cn.tedu.lucky.draw.server.common.enums.ErrorEnum;
import cn.tedu.lucky.draw.server.common.handler.DrawException;
import cn.tedu.lucky.draw.server.protocol.po.ActivityRule;
import cn.tedu.lucky.draw.server.protocol.po.Rule;
import cn.tedu.lucky.draw.server.repository.ActivityRuleRepository;
import cn.tedu.lucky.draw.server.repository.RuleRepository;
import cn.tedu.lucky.draw.server.service.IActivityRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ActivityRuleServiceImpl implements IActivityRuleService {

    @Autowired
    private ActivityRuleRepository activityRuleRepository;

    @Autowired
    private RuleRepository ruleRepository;

    @Override
    public List<Rule> findRulesByActivityId(Long id) {
        List<ActivityRule> activityRuleList=activityRuleRepository.findByActivityId(id);
        List<Long> ids = activityRuleList.stream().map(ActivityRule::getRuleId).collect(Collectors.toList());
        return ruleRepository.findAllById(ids);
    }

    @Override
    public List<Rule> findNoBindRule(Long id) {
        List<ActivityRule> activityRuleList = activityRuleRepository.findByActivityId(id);
        ArrayList<Long> excluedIds = new ArrayList<>();
        for (ActivityRule activityRule : activityRuleList) {
            excluedIds.add(activityRule.getRuleId());
        }
        Integer status = Integer.valueOf(DrawEnum.ENABLE.getCode());
        if (excluedIds.size()==0 || excluedIds ==null){
            return ruleRepository.findByStatusEquals(status);
        }
        return ruleRepository.findByIdNotInAndStatusEquals(excluedIds,status);

    }

    @Override
    public void saveAll(List<ActivityRule> activityRuleList) {
        List<ActivityRule> activityRules = activityRuleRepository.saveAll(activityRuleList);
        if (activityRules==null || activityRules.size()==0){
            throw new DrawException(ErrorEnum.SYSTEM_ERROR);
        }
    }
}
